import * as Cesium from '@cesiumjs';
import G3vViewers from "./viewers";
import {G3vOverviewer} from "./viewers/viewer";
import {
  g3x_defineProperty,
  g3x_defineReadonly
} from "@g3x/utils";
import {
  defaultViews
} from "./defaultOptions";

(0, function() {
  //Rectangle(west, south, east, north)
  let rectangle = Cesium.Rectangle.fromDegrees(19, -2, -162, 70);
  rectangle = defaultViews.global.china.rectangle;
  Cesium.Camera.DEFAULT_VIEW_RECTANGLE = rectangle
})();

class G3V {

  constructor(g3vOptions, readyCallback) {
    console.log("G3V constructor!")

    let _this = this;

    _this.readyCallbacks = [readyCallback];

    g3x_defineProperty(_this, "isReady", false, null, (newValue)=>{
      if(newValue){
        _this.readyCallbacks.forEach(callback=>{
          callback&&callback()
        })
        _this.readyCallbacks.splice(0)
      }
    })

    _this.g3vOptions = g3vOptions;

    if(g3vOptions.defaultViewRectangle){
      Cesium.Camera.DEFAULT_VIEW_RECTANGLE = g3vOptions.defaultViewRectangle
    }

    const g3vViewers = new G3vViewers(g3vOptions, _this)

    g3x_defineReadonly(_this, "g3vViewers", g3vViewers);

    _this.createOverview()

    setTimeout(()=>{
      _this.isReady = true;
    },1000)
  }

  createOverview(){
    const {g3vOptions,g3vViewers} = this;
    const {overview,viewers} = g3vOptions;
    if(!overview) return;

    const g3vOverviewer = new G3vOverviewer(overview, this);

    g3x_defineReadonly(this, "g3vOverviewer", g3vOverviewer);
    g3x_defineReadonly(this, "overviewer", g3vOverviewer.viewer);

    viewers.forEach((e,i)=>{
      if(e.overview){
        const g3vViewer = g3vViewers.get(i)
        g3vOverviewer.add(g3vViewer)
      }
    })

    return g3vOverviewer;
  }

  ready(callback){
    if(this.isReady){
      return callback&&callback()
    }
    this.readyCallbacks.push(callback)
  }

  destroy(){
    const {g3vViewers,g3vOverviewer} = this;
    g3vOverviewer && g3vOverviewer.destroy()
    g3vViewers && g3vViewers.destroy()
  }
}

export default G3V;
export {G3V};
